<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>科幻弹幕墙 - 文档管理系统</title>
    <link rel="stylesheet" href="/css/style.css">
    <link rel="preload" href="/css/danmaku.css" as="style">
    <link rel="preload" href="/js/danmaku.js" as="script">
    <link rel="dns-prefetch" href="https://api.dicebear.com">
    <style>
        body, html {
            margin: 0;
            padding: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
            background: linear-gradient(135deg, #000f1a, #001a2b);
            font-family: Arial, sans-serif;
            color: #fff;
        }
        
        .danmaku-wall-container {
            position: relative;
            width: 100%;
            height: 100vh;
            overflow: hidden;
            background-size: cover;
            background-position: center;
            transition: background-image 1s ease-in-out;
        }
        
        .overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 10, 30, 0.2);
            z-index: 1;
        }
        
        .header {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            padding: 10px 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: rgba(0, 20, 40, 0.01);
            border-bottom: 1px solid rgba(10, 132, 255, 0.01);
            z-index: 1000;
            transition: all 0.3s;
        }
        
        .header:hover {
            background: rgba(0, 20, 40, 0.05);
            border-bottom: 1px solid rgba(10, 132, 255, 0.05);
        }
        
        .header h1 {
            font-size: 1.8rem;
            margin: 0;
            color: rgba(78, 242, 248, 0.4);
            text-shadow: 0 0 8px rgba(78, 242, 248, 0.1);
            font-family: 'Orbitron', sans-serif;
            font-weight: 500;
            text-transform: uppercase;
            letter-spacing: 3px;
        }
        
        .controls {
            display: flex;
            gap: 15px;
        }
        
        .controls button, .controls select {
            background: rgba(10, 132, 255, 0.01);
            border: 1px solid rgba(78, 242, 248, 0.03);
            color: rgba(255, 255, 255, 0.4);
            padding: 10px 20px;
            border-radius: 25px;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 1.3rem;
            outline: none;
            box-shadow: none;
        }
        
        .controls button:hover, .controls select:hover {
            background: rgba(10, 132, 255, 0.05);
            box-shadow: 0 0 5px rgba(78, 242, 248, 0.05);
            color: rgba(255, 255, 255, 0.7);
            transform: translateY(-2px);
        }
        
        .opacity-control {
            display: flex;
            align-items: center;
            gap: 8px;
            background: rgba(10, 132, 255, 0.01);
            border: 1px solid rgba(78, 242, 248, 0.03);
            border-radius: 25px;
            padding: 5px 15px;
            box-shadow: none;
            transition: all 0.3s;
        }
        
        .opacity-control:hover {
            background: rgba(10, 132, 255, 0.05);
            border: 1px solid rgba(78, 242, 248, 0.05);
        }
        
        .opacity-control label {
            color: rgba(255, 255, 255, 0.4);
            font-size: 1.1rem;
            white-space: nowrap;
        }
        
        .opacity-control:hover label {
            color: rgba(255, 255, 255, 0.7);
        }
        
        .opacity-control input[type="range"] {
            width: 80px;
            height: 6px;
            -webkit-appearance: none;
            background: linear-gradient(to right, rgba(0, 0, 0, 0.05), rgba(0, 0, 0, 0.1));
            border-radius: 5px;
            outline: none;
        }
        
        .opacity-control input[type="range"]::-webkit-slider-thumb {
            -webkit-appearance: none;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: rgba(78, 242, 248, 0.3);
            cursor: pointer;
            box-shadow: 0 0 3px rgba(78, 242, 248, 0.1);
        }
        
        .opacity-control input[type="range"]::-moz-range-thumb {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: rgba(78, 242, 248, 0.3);
            cursor: pointer;
            box-shadow: 0 0 3px rgba(78, 242, 248, 0.1);
        }
        
        .danmaku-area {
            width: 100%;
            height: 100%;
            position: relative;
            padding-top: 60px;
            padding-bottom: 60px;
            box-sizing: border-box;
            z-index: 10;
            overflow: hidden;
        }
        
        .danmaku-item {
            position: absolute;
            display: inline-block;
            padding: 8px 20px;
            border-radius: 25px;
            color: #fff;
            font-size: 1.7rem;
            white-space: nowrap;
            box-shadow: 0 0 8px rgba(78, 242, 248, 0.2);
            z-index: 9;
            opacity: 0.9;
            left: -300px; /* 初始位置在左侧屏幕外 */
            animation-name: none; /* 不使用关键帧动画，改用JavaScript控制 */
            transition: left 10s linear;
        }
        
        .danmaku-item.type-1 {
            background: rgba(10, 132, 255, 0.2);
            border: 1px solid rgba(10, 132, 255, 0.4);
            box-shadow: 0 0 15px rgba(10, 132, 255, 0.3);
            text-shadow: 0 0 6px rgba(10, 132, 255, 0.7);
        }
        
        .danmaku-item.type-2 {
            background: rgba(0, 199, 190, 0.2);
            border: 1px solid rgba(0, 199, 190, 0.4);
            box-shadow: 0 0 15px rgba(0, 199, 190, 0.3);
            text-shadow: 0 0 6px rgba(0, 199, 190, 0.7);
        }
        
        .danmaku-item.type-3 {
            background: rgba(94, 92, 230, 0.2);
            border: 1px solid rgba(94, 92, 230, 0.4);
            box-shadow: 0 0 15px rgba(94, 92, 230, 0.3);
            text-shadow: 0 0 6px rgba(94, 92, 230, 0.7);
        }
        
        .danmaku-item.type-4 {
            background: rgba(255, 55, 95, 0.2);
            border: 1px solid rgba(255, 55, 95, 0.4);
            box-shadow: 0 0 15px rgba(255, 55, 95, 0.3);
            text-shadow: 0 0 6px rgba(255, 55, 95, 0.7);
        }
        
        .danmaku-item.type-5 {
            background: rgba(255, 159, 10, 0.2);
            border: 1px solid rgba(255, 159, 10, 0.4);
            box-shadow: 0 0 15px rgba(255, 159, 10, 0.3);
            text-shadow: 0 0 6px rgba(255, 159, 10, 0.7);
        }
        
        .username {
            font-weight: bold;
            margin-right: 8px;
            color: #4ef2f8;
            font-size: 1.7rem;
        }
        
        .footer {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 15px 20px;
            background: rgba(0, 20, 40, 0.01);
            border-top: 1px solid rgba(10, 132, 255, 0.01);
            z-index: 1000;
            transition: all 0.3s;
        }
        
        .footer:hover {
            background: rgba(0, 20, 40, 0.05);
            border-top: 1px solid rgba(10, 132, 255, 0.05);
        }
        
        .input-container {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            max-width: 800px;
            margin: 0 auto;
            background: transparent;
        }
        
        .danmaku-input {
            flex: 1;
            background: rgba(255, 255, 255, 0.01);
            border: 1px solid rgba(78, 242, 248, 0.03);
            border-radius: 25px;
            padding: 12px 20px;
            color: rgba(255, 255, 255, 0.6);
            outline: none;
            font-size: 1.4rem;
            transition: all 0.3s;
        }
        
        .danmaku-input:focus {
            border-color: rgba(78, 242, 248, 0.1);
            box-shadow: 0 0 5px rgba(78, 242, 248, 0.05);
            background: rgba(255, 255, 255, 0.03);
        }
        
        .danmaku-send {
            background: rgba(10, 132, 255, 0.01);
            color: rgba(255, 255, 255, 0.4);
            border: 1px solid rgba(78, 242, 248, 0.03);
            border-radius: 25px;
            padding: 12px 35px;
            margin-left: 15px;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 1.4rem;
            font-weight: bold;
            text-shadow: none;
            box-shadow: none;
        }
        
        .danmaku-send:hover {
            transform: translateY(-2px);
            background: rgba(10, 132, 255, 0.05);
            color: rgba(255, 255, 255, 0.7);
            box-shadow: 0 0 5px rgba(78, 242, 248, 0.05);
        }
        
        .grid {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-image: linear-gradient(rgba(10, 132, 255, 0.01) 1px, transparent 1px),
                             linear-gradient(90deg, rgba(10, 132, 255, 0.01) 1px, transparent 1px);
            background-size: 50px 50px;
            z-index: 2;
        }
        
        .back-to-dashboard {
            position: absolute;
            bottom: 80px;
            right: 20px;
            padding: 10px 20px;
            background: rgba(0, 20, 40, 0.01);
            color: rgba(255, 255, 255, 0.4);
            border: 1px solid rgba(10, 132, 255, 0.01);
            border-radius: 25px;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 1.2rem;
            text-decoration: none;
            z-index: 1000;
        }
        
        .back-to-dashboard:hover {
            background: rgba(0, 20, 40, 0.05);
            border-color: rgba(10, 132, 255, 0.05);
            color: rgba(255, 255, 255, 0.7);
            transform: translateY(-2px);
        }
        
        .particles {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
            z-index: 3;
        }
        
        .particle {
            position: absolute;
            border-radius: 50%;
            background-color: rgba(78, 242, 248, 0.3);
            pointer-events: none;
            z-index: 1;
        }
        
        .bg-settings {
            position: fixed;
            right: 20px;
            top: 60px;
            z-index: 101;
            background: rgba(0, 20, 40, 0.8);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(10, 132, 255, 0.3);
            border-radius: 10px;
            padding: 15px;
            display: none;
            flex-direction: column;
            gap: 10px;
            box-shadow: 0 0 20px rgba(10, 132, 255, 0.2);
        }
        
        .bg-settings.active {
            display: flex;
        }
        
        .bg-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 10px;
            max-height: 300px;
            overflow-y: auto;
        }
        
        .bg-item {
            width: 100px;
            height: 60px;
            background-size: cover;
            background-position: center;
            border-radius: 5px;
            cursor: pointer;
            border: 2px solid transparent;
            transition: all 0.3s;
        }
        
        .bg-item:hover, .bg-item.active {
            border-color: #4ef2f8;
            transform: scale(1.05);
            box-shadow: 0 0 15px rgba(78, 242, 248, 0.5);
        }
        
        .upload-bg {
            margin-top: 10px;
            display: none;
        }
        
        .settings-title {
            font-size: 1rem;
            margin-bottom: 10px;
            color: #4ef2f8;
            text-align: center;
        }
        
        @keyframes floating {
            0% { transform: translateY(0px); }
            50% { transform: translateY(-10px); }
            100% { transform: translateY(0px); }
        }
        
        @keyframes text-flicker {
            0% { text-shadow: 0 0 10px rgba(78, 242, 248, 0.5); }
            25% { text-shadow: 0 0 15px rgba(78, 242, 248, 0.7); }
            50% { text-shadow: 0 0 20px rgba(78, 242, 248, 0.9); }
            75% { text-shadow: 0 0 15px rgba(78, 242, 248, 0.7); }
            100% { text-shadow: 0 0 10px rgba(78, 242, 248, 0.5); }
        }
        
        @keyframes scanner {
            0% { transform: translateY(-100%); }
            100% { transform: translateY(100%); }
        }
        
        .scanner-line {
            position: absolute;
            left: 0;
            width: 100%;
            height: 1px;
            background: linear-gradient(to right, 
                rgba(78, 242, 248, 0), 
                rgba(78, 242, 248, 0.4), 
                rgba(78, 242, 248, 0));
            box-shadow: 0 0 8px rgba(78, 242, 248, 0.4);
            z-index: 4;
            animation: scanner 10s linear infinite;
        }
    </style>
</head>
<body>
    <div class="danmaku-wall-container" id="danmaku-container" th:style="${backgroundImage != '' ? 'background-image: url(' + backgroundImage + ')' : ''}">
        <div class="overlay" th:style="${backgroundImage != '' ? 'background-color: rgba(0,0,0,' + backgroundOpacity + ')' : 'background: rgba(0, 10, 30, 0.7)'}"></div>
        <div class="grid"></div>
        <div class="particles" id="particles"></div>
        <div class="scanner-line"></div>
        
        <div class="header">
            <div class="title">
                <svg width="32" height="32" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                    <path d="M20 2H4C2.9 2 2 2.9 2 4V16C2 17.1 2.9 18 4 18H18L22 22V4C22 2.9 21.1 2 20 2ZM20 17.17L18.83 16H4V4H20V17.17Z" fill="#4ef2f8"/>
                    <path d="M6 12H18V14H6V12ZM6 9H18V11H6V9ZM6 6H18V8H6V6Z" fill="#4ef2f8"/>
                </svg>
                <span></span>
            </div>
            <div class="controls">
                <button id="pause-button">暂停</button>
                <button id="speed-button">加速</button>
                <div class="opacity-control">
                    <label for="bg-opacity">透明度</label>
                    <input type="range" id="bg-opacity" min="0" max="1" step="0.1" th:value="${backgroundOpacity ?: '0.5'}">
                </div>
                <select id="lanes-select">
                    <option value="5">5 轨道</option>
                    <option value="10" selected>10 轨道</option>
                    <option value="15">15 轨道</option>
                    <option value="20">20 轨道</option>
                </select>
                <button id="fullscreen-button">全屏</button>
            </div>
        </div>
        
        <div class="danmaku-area" id="danmaku-area">
            <!-- 弹幕将在这里动态生成 -->
        </div>
        
        <div class="footer">
            <div class="input-container">
                <input type="text" class="danmaku-input" id="danmaku-input" placeholder="发送一条科幻消息..." th:disabled="${user == null}">
                <button class="danmaku-send" id="danmaku-send" th:disabled="${user == null}">发送</button>
            </div>
        </div>
        
        <a href="/dashboard" class="back-to-dashboard">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style="margin-right: 5px;">
                <path d="M10 20V14H14V20H19V12H22L12 3L2 12H5V20H10Z" fill="#4ef2f8"/>
            </svg>
            返回控制面板
        </a>
    </div>
    
    <script>
        // 延迟加载非关键资源
        window.addEventListener('load', function() {
            // 动态加载非关键脚本或样式表
            setTimeout(function() {
                const link = document.createElement('link');
                link.rel = 'stylesheet';
                link.href = '/css/animations.css';
                document.head.appendChild(link);
            }, 1000);
        });
    </script>
    
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const danmakuContainer = document.getElementById('danmaku-area');
            const danmakuArea = document.getElementById('danmaku-area');
            const danmakuInput = document.getElementById('danmaku-input');
            const danmakuSend = document.getElementById('danmaku-send');
            const pauseButton = document.getElementById('pause-button');
            const speedButton = document.getElementById('speed-button');
            const lanesSelect = document.getElementById('lanes-select');
            const fullscreenButton = document.getElementById('fullscreen-button');
            const particlesContainer = document.getElementById('particles');
            const header = document.querySelector('.header');
            const footer = document.querySelector('.footer');
            const opacitySlider = document.getElementById('bg-opacity');
            const overlay = document.querySelector('.overlay');
            
            let isPaused = false;
            let baseSpeed = 15; // 基础速度（秒）
            let speedMultiplier = 1; // 速度倍数
            let maxLanes = parseInt(lanesSelect.value); // 轨道数量
            let autoHideTimer = null;
            
            // 全局变量
            let danmakuQueue = []; // 弹幕队列
            let isFirstLoad = true; // 是否首次加载
            let danmakuLoopInterval = null; // 弹幕循环定时器
            let loadingData = false; // 是否正在加载数据
            let pendingSendRequests = []; // 待发送的弹幕请求队列
            let displayRequestAnimationFrameId = null; // requestAnimationFrame ID
            
            // 弹幕渲染优化
            const bufferSize = 50; // 预加载弹幕数量
            let visibleDanmakuElements = new Map(); // 当前可见的弹幕元素
            
            // 虚拟化渲染 - 限制同时显示的弹幕数量
            const MAX_VISIBLE_DANMAKU = 20; // 最大同时显示弹幕数
            
            // 检测设备性能并调整配置
            const detectDevicePerformance = () => {
                const lowPerformance = window.navigator.hardwareConcurrency < 4 || 
                                      /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
                
                if (lowPerformance) {
                    // 降低效果适应低性能设备
                    baseSpeed = 20; // 放慢速度
                    return 10; // 低性能设备最多显示10条弹幕
                }
                
                return MAX_VISIBLE_DANMAKU;
            };
            
            // 设置最大可见弹幕数量
            const maxVisibleDanmaku = detectDevicePerformance();
            
            // 定义用于计算每个轨道使用次数的映射
            const trackUsageCounts = new Map();
            // 在屏幕高度范围内定义多个轨道
            const tracks = {
                'top': { y: 10, usageCount: 0, elements: [] },
                'middle': { y: Math.floor(window.innerHeight / 2) - 30, usageCount: 0, elements: [] },
                'bottom': { y: window.innerHeight - 70, usageCount: 0, elements: [] }
            };
            
            // 初始化轨道
            function initTracks() {
                const lanes = parseInt(lanesSelect.value);
                // 清空现有轨道
                Object.keys(tracks).forEach(key => {
                    delete tracks[key];
                });
                
                // 计算轨道间距
                const spacing = window.innerHeight / (lanes + 1);
                
                // 创建轨道
                for (let i = 0; i < lanes; i++) {
                    const yPos = Math.floor(spacing * (i + 1));
                    tracks[`lane-${i}`] = { y: yPos, usageCount: 0, elements: [] };
                }
            }
            
            // 获取使用最少的轨道
            function getLeastUsedLane() {
                return Object.keys(tracks).reduce((leastUsed, current) => {
                    if (!leastUsed || tracks[current].usageCount < tracks[leastUsed].usageCount) {
                        return current;
                    }
                    return leastUsed;
                }, null);
            }
            
            // 使用防抖优化来初始化轨道
            let resizeTimeout;
            window.addEventListener('resize', function() {
                if (resizeTimeout) {
                    clearTimeout(resizeTimeout);
                }
                resizeTimeout = setTimeout(function() {
                    initTracks();
                    initParticles();
                }, 200);
            });
            
            // 开始弹幕循环
            function startDanmakuLoop() {
                // 如果已有循环播放，先清除
                if (danmakuLoopInterval) {
                    clearInterval(danmakuLoopInterval);
                    danmakuLoopInterval = null;
                }
                
                // 创建新的循环
                danmakuLoopInterval = setInterval(() => {
                    if (isPaused || !danmakuQueue || danmakuQueue.length === 0) {
                        return;
                    }
                    
                    // 随机选择最多3条弹幕添加
                    const count = Math.min(3, danmakuQueue.length);
                    for (let i = 0; i < count; i++) {
                        const index = Math.floor(Math.random() * danmakuQueue.length);
                        const danmaku = danmakuQueue[index];
                        // 使用rAF添加弹幕
                        if (displayRequestAnimationFrameId === null) {
                            displayRequestAnimationFrameId = requestAnimationFrame(() => {
                                addDanmaku(danmaku);
                                displayRequestAnimationFrameId = null;
                            });
                        }
                    }
                }, 1000); // 每秒批量添加弹幕
            }
            
            // 添加一条弹幕到屏幕，从左到右显示
            function addDanmaku(danmaku, forcedLane = null) {
                if (!danmaku || typeof danmaku !== 'object' || !danmaku.content || isPaused) {
                    return;
                }
                
                // 如果已经达到最大同时显示弹幕数，延迟显示或丢弃
                if (visibleDanmakuElements.size >= maxVisibleDanmaku) {
                    // 移除最早的一条弹幕
                    const oldestKey = visibleDanmakuElements.keys().next().value;
                    if (oldestKey) {
                        const oldest = visibleDanmakuElements.get(oldestKey);
                        if (oldest && oldest.element && oldest.element.parentNode) {
                            oldest.element.parentNode.removeChild(oldest.element);
                            visibleDanmakuElements.delete(oldestKey);
                        }
                    }
                }
                
                // 创建弹幕元素
                const element = document.createElement('div');
                element.className = 'danmaku-item';
                
                // 设置弹幕内容
                const content = danmaku.content;
                if (danmaku.user && danmaku.user.username) {
                    element.innerHTML = `<span class="username">${danmaku.user.username}</span>${content}`;
                } else {
                    element.textContent = content;
                }
                
                // 设置弹幕颜色类型
                const colorType = danmaku.colorType || Math.floor(Math.random() * 5) + 1;
                element.classList.add(`type-${colorType}`);
                
                // 选择弹幕显示的轨道
                const laneKey = forcedLane || getLeastUsedLane();
                const lane = tracks[laneKey];
                
                // 更新轨道使用计数
                lane.usageCount++;
                
                // 设置弹幕在屏幕上的初始位置
                element.style.top = `${lane.y}px`;
                element.style.right = '-300px';
                
                // 设置转换样式以确保GPU加速
                element.style.transform = 'translateZ(0)';
                element.style.willChange = 'transform';
                
                // 添加到容器
                danmakuContainer.appendChild(element);
                
                // 计算动画持续时间（距离/速度）
                const speed = baseSpeed / speedMultiplier;
                const duration = speed + (Math.random() * 2 - 1); // 添加一点随机性
                
                // 添加到可见元素集合
                const elementId = Date.now() + '-' + Math.floor(Math.random() * 1000);
                element.dataset.id = elementId;
                visibleDanmakuElements.set(elementId, { element, lane: laneKey });
                
                // 运行动画
                setTimeout(() => {
                    element.classList.add('show');
                    element.style.transition = `transform ${duration}s linear, opacity 0.5s ease`;
                    element.style.transform = 'translateX(-2000px)';
                }, 20);
                
                // 动画结束后移除元素
                setTimeout(() => {
                    if (element.parentNode) {
                        element.classList.remove('show');
                        setTimeout(() => {
                            if (element.parentNode) {
                                element.parentNode.removeChild(element);
                                lane.usageCount = Math.max(0, lane.usageCount - 1);
                                visibleDanmakuElements.delete(elementId);
                            }
                        }, 500);
                    }
                }, duration * 1000 + 500);
            }
            
            // 初始化粒子背景（性能优化）
            function initParticles() {
                if (!particlesContainer) return;
                
                particlesContainer.innerHTML = '';
                
                // 根据屏幕大小调整粒子数量
                const particleCount = Math.min(50, Math.floor((window.innerWidth * window.innerHeight) / 15000));
                
                for (let i = 0; i < particleCount; i++) {
                    const particle = document.createElement('div');
                    particle.className = 'particle';
                    particle.style.top = Math.random() * 100 + '%';
                    particle.style.left = Math.random() * 100 + '%';
                    particle.style.width = Math.random() * 3 + 1 + 'px';
                    particle.style.height = particle.style.width;
                    particle.style.animationDuration = Math.random() * 20 + 10 + 's';
                    particle.style.animationDelay = Math.random() * 5 + 's';
                    particlesContainer.appendChild(particle);
                }
            }
            
            // 懒加载图片和头像
            function lazyLoadImages() {
                const images = document.querySelectorAll('.lazy-load');
                if ('IntersectionObserver' in window) {
                    const imageObserver = new IntersectionObserver((entries, observer) => {
                        entries.forEach(entry => {
                            if (entry.isIntersecting) {
                                const image = entry.target;
                                image.src = image.dataset.src;
                                image.classList.remove('lazy-load');
                                imageObserver.unobserve(image);
                            }
                        });
                    });
                    
                    images.forEach(image => imageObserver.observe(image));
                } else {
                    // 回退方案
                    images.forEach(image => {
                        image.src = image.dataset.src;
                        image.classList.remove('lazy-load');
                    });
                }
            }
            
            // 使用Web Worker处理弹幕数据（如果浏览器支持）
            let dataWorker = null;
            
            function initWebWorker() {
                if (window.Worker) {
                    try {
                        const workerCode = `
                            self.onmessage = function(e) {
                                const data = e.data;
                                if (data.action === 'process') {
                                    // 处理和过滤弹幕数据
                                    const processedData = data.danmakus
                                        .filter(d => d && d.content) // 过滤无效数据
                                        .sort(() => Math.random() - 0.5); // 随机排序
                                    
                                    self.postMessage({
                                        action: 'processed',
                                        data: processedData
                                    });
                                }
                            };
                        `;
                        
                        const blob = new Blob([workerCode], {type: 'application/javascript'});
                        dataWorker = new Worker(URL.createObjectURL(blob));
                        
                        dataWorker.onmessage = function(e) {
                            const message = e.data;
                            if (message.action === 'processed') {
                                danmakuQueue = message.data;
                                if (isFirstLoad) {
                                    isFirstLoad = false;
                                    batchDisplayInitialDanmakus();
                                }
                            }
                        };
                    } catch (e) {
                        console.error('Web Worker初始化失败:', e);
                        dataWorker = null;
                    }
                }
            }
            
            // 加载弹幕数据，使用批量加载和缓存
            function loadDanmakus() {
                if (loadingData) return; // 防止重复加载
                
                loadingData = true;
                
                // 设置超时，防止加载卡死
                const loadingTimeout = setTimeout(() => {
                    loadingData = false;
                }, 10000);
                
                // 从API获取数据
                fetch('/danmaku/api/list')
                    .then(response => response.json())
                    .then(data => {
                        clearTimeout(loadingTimeout);
                        loadingData = false;
                        
                        if (data && data.length > 0) {
                            // 使用Web Worker处理数据
                            if (dataWorker) {
                                dataWorker.postMessage({
                                    action: 'process',
                                    danmakus: data
                                });
                            } else {
                                // 降级处理
                                danmakuQueue = [...data];
                                
                                // 如果是首次加载，立即显示一些弹幕
                                if (isFirstLoad) {
                                    isFirstLoad = false;
                                    batchDisplayInitialDanmakus();
                                }
                            }
                        }
                    })
                    .catch(error => {
                        console.error('加载弹幕失败:', error);
                        clearTimeout(loadingTimeout);
                        loadingData = false;
                    });
            }
            
            // 批量显示初始弹幕
            function batchDisplayInitialDanmakus() {
                // 确保有足够的弹幕数据
                if (danmakuQueue.length === 0) return;
                
                // 随机选择弹幕显示
                const displayCount = Math.min(5, danmakuQueue.length);
                const laneKeys = Object.keys(tracks);
                
                // 使用rAF优化渲染
                requestAnimationFrame(() => {
                    for (let i = 0; i < displayCount; i++) {
                        const index = Math.floor(Math.random() * danmakuQueue.length);
                        const danmaku = danmakuQueue[index];
                        // 为每条弹幕分配一个轨道
                        const laneKey = laneKeys[i % laneKeys.length];
                        addDanmaku(danmaku, laneKey);
                    }
                });
            }
            
            // 发送弹幕（优化版）
            function sendDanmaku() {
                const text = danmakuInput.value.trim();
                if (!text) return;
                
                const colorType = Math.floor(Math.random() * 5) + 1;
                
                // 添加到待发送队列
                const requestData = {
                    content: text,
                    colorType: colorType
                };
                
                // 立即在本地添加一条临时弹幕
                const tempDanmaku = {
                    id: -1,
                    content: text,
                    colorType: colorType,
                    createdTime: new Date().toISOString(),
                    user: window.currentUser || null // 当前登录用户信息
                };
                
                // 显示临时弹幕
                addDanmaku(tempDanmaku);
                
                // 清空输入框
                danmakuInput.value = '';
                
                // 发送到服务器
                fetch('/danmaku/api/send', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `content=${encodeURIComponent(text)}&colorType=${colorType}`
                })
                .catch(error => {
                    console.error('发送弹幕失败:', error);
                });
            }
            
            // 初始化
            function initialize() {
                // 初始化Web Worker
                initWebWorker();
                
                // 初始化轨道
                initTracks();
                
                // 初始化粒子背景
                initParticles();
                
                // 加载弹幕数据
                loadDanmakus();
                
                // 开始弹幕循环
                startDanmakuLoop();
                
                // 周期性重新加载数据（每60秒）
                setInterval(loadDanmakus, 60000);
                
                // 初始化延迟加载图片
                window.addEventListener('load', lazyLoadImages);
            }
            
            // 发送弹幕按钮点击事件
            danmakuSend.addEventListener('click', sendDanmaku);
            
            // 按Enter键发送弹幕
            danmakuInput.addEventListener('keypress', function(event) {
                if (event.key === 'Enter') {
                    sendDanmaku();
                }
            });
            
            // 初始化页面
            initialize();
        });
    </script>
</body>
</html>